package com.we823.cms.core.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.we823.cms.common.WebConstants;
import com.we823.cms.common.web.FrontUtils;
import com.we823.cms.model.sys.Config;

public class FrontSiteConfigInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(FrontSiteConfigInterceptor.class);
	
	@Autowired
	private FrontUtils frontUtils;
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		logger.debug("frontSite postHandle");
		if(modelAndView!=null){
			String viewUrl = modelAndView.getViewName();
			logger.debug("viewUrl:{}",viewUrl);
			if(StringUtils.contains(viewUrl, "redirect:")){
				return;
			}
			Map<String, Object> model = modelAndView.getModel();
			if(!model.containsKey(WebConstants.CONFIG_KEY)){
				Config configModel = frontUtils.getCurrentConfigModel();
				model.put(WebConstants.CONFIG_KEY, configModel);
			}
			if(model.containsKey(WebConstants.CONFIG_KEY))
			{
				Config configModel = (Config) model.get(WebConstants.CONFIG_KEY);
				Boolean isIndex = (Boolean) model.get(WebConstants.URL_ISINDEX);
				String currentTheme = "defualt";
				String index = "index";
				if(configModel!=null){
					currentTheme = configModel.getCurrentTheme();
					index = configModel.getIndex();
				}
				if(isIndex!=null && isIndex==true){
					viewUrl = String.format(viewUrl, currentTheme,index);
				}else{
					viewUrl = String.format(viewUrl, currentTheme);
				}
				
				model.put(WebConstants.CURRENT_THEME, currentTheme);
				modelAndView.setViewName(viewUrl);
			}
			logger.debug("viewUrl:{}",viewUrl);
			model.put(WebConstants.CONTEXT_PATH, request.getContextPath());
			
		}
		logger.debug("frontSite postHandle uri:{}",request.getRequestURI());
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.debug("frontSite preHandle");
		logger.debug("frontSite preHandle uri:{}",request.getRequestURI());
		return true;
	}

	public FrontUtils getFrontUtils() {
		return frontUtils;
	}

	public void setFrontUtils(FrontUtils frontUtils) {
		this.frontUtils = frontUtils;
	}
}
